<template>
  <div style="padding: 0 10px;">
    <h4>发表评论</h4>
    <hr />
    <van-cell-group>
      <van-field
        v-model="content"
        rows="1"
        autosize
        type="textarea"
        placeholder="请输入留言"
      />
    </van-cell-group>
    <van-button type="info" size="large" @click="addContent"
      >发表评论</van-button
    >
    <van-list v-for="(item, i) in commentsList" :key="i">
      <div class="title">
        <span>第{{ i + 1 }}楼</span>
        <span>用户: {{ item.user_name }}</span>
        <span>发表时间: {{ item.add_time | dateFormat }}</span>
      </div>
      <div class="content">{{ item.content }}</div>
    </van-list>
    <van-button plain hairline type="danger" size="large" @click="addMore"
      >加载更多</van-button
    >
  </div>
</template>

<script>
export default {
  props: ['id'],
  data() {
    return {
      content: '',
      commentsList: [],
      pageSize: 1
    }
  },
  created() {
    this.getComments()
  },
  methods: {
    async getComments() {
      const { data: res } = await this.axios.get(
        '/api/getcomments/' + this.id + '?pageindex=' + this.pageSize
      )
      if (res.status !== 0) {
        return this.$toast('获取评论列表失败')
      }
      this.commentsList = res.message
    },
    // 点击按钮 加载更多
    async addMore() {
      this.pageSize++
      const { data: res } = await this.axios.get(
        '/api/getcomments/' + this.id + '?pageindex=' + this.pageSize
      )
      if (res.status !== 0) {
        return this.$toast('获取评论列表失败')
      }
      this.commentsList.push(...res.message)
    },
    // 添加评论
    async addContent() {
      if (this.content.trim().length === 0) {
        return this.$toast('评论内容不能为空,请填写内容')
      }
      const { data: res } = await this.axios.post(
        '/api/postcomment/' + this.id,
        { content: this.content }
      )
      if (res.status !== 0) {
        return this.$toast('发表评论失败')
      }
      this.$toast('评论成功')
      this.content = ''
      this.getComments()
    }
  }
}
</script>

<style lang="less" scoped>
.van-field {
  height: 100px;
  border: 1px solid #ccc;
}
.van-button {
  margin: 5px 0;
}
.title {
  height: 25px;
  background-color: #ccc;
  font-size: 12px;
  line-height: 25px;
  span {
    margin-right: 6px;
  }
}
.content {
  line-height: 30px;
  text-indent: 2em;
  font-size: 12px;
}
</style>
